package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Value("${leadnews.jwt.expire}")
    private Integer expire;

    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath;

    @Override
    public ResponseResult<Map<String, Object>> login(LoginDto dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        //判断参数
        if (StringUtils.isNotEmpty(phone) && StringUtils.isNotEmpty(password)) {
            QueryWrapper<ApUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone); //.select("id","password") 指定查询字段
            ApUser apUser = getOne(queryWrapper);

            //查询用户名存在
            if (apUser == null) {
                throw new LeadNewsException(501,"用户不存在");
            }

            if (!BCrypt.checkpw(password, apUser.getPassword())) {
                throw new LeadNewsException(501,"密码错误");
            }

            apUser.setPassword(null);

            Map<String, Object> resultMap = CreateTokenAndResponse(apUser);
            return ResponseResult.okResult(resultMap);
        } else {
            ApUser apUser = new ApUser();
            apUser.setId(0);

            Map<String, Object> resultMap = CreateTokenAndResponse(apUser);
            return ResponseResult.okResult(resultMap);
        }

    }

    private Map<String, Object> CreateTokenAndResponse(ApUser apUser) {
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
            String token = JwtUtils.generateTokenExpireInMinutes(apUser, privateKey, 30);

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("token", token);
            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
